<template>
  <!--轮播广告banner-->
    <div class="ad_swipe" v-if="adList.length">
      <swiper class="swiper" :options="adSwiperOption" v-if="adList.length" @click.native="handleClickSlide" ref="swiper">
        <swiper-slide v-for="item in adList" :key="item.id">
          <div class="ad_img">
            <img :src="item.picUrl" @error="imgError(item)"/>
            </div>
        </swiper-slide>
        <div class="swiper-pagination ad_swiper_pagination" slot="pagination"></div>
      </swiper>
    </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { Swiper, SwiperSlide } from 'vue-awesome-swiper';
import tracking from '@/utils/tracking.js';

// 广告轮播组件参数
const adSwiperOption = {
  autoplay: { // 自动轮播
    enabled: true,
    delay: 3000
  },
  slidesPerView: 1,
  spaceBetween: 10,
  loop: true, // 可循环
  pagination: {
    el: '.ad_swiper_pagination',
    // clickable: true
  },
};

let AppUtils;
let DZUtils;
export default {
  name: 'adSwiper',
  mixins: [
    tracking
  ],
  components: {
    Swiper,
    SwiperSlide,
  },
  computed: mapState(['adList']),
  data() {
    return {
      // 广告轮播组件参数
      adSwiperOption,
    };
  },
  props: ['serverCacheKey'],
  beforeMount() {
    AppUtils = require('@/utils/appUtils').default;
    DZUtils = require('@/utils/appUtils').default;
  },
  methods: {
    goToProduct(product) {
      // TD埋点 CNZZ埋点
      this.buryEventPoint('H5-GDBA-EVENT', product.name);
      this.buryEventPointCNZZ('H5-GDBA-EVENT', product.name);
      const redirectUrl = AppUtils.native.getRedirectUrl(product);
      // 用全局的跳转方法，尽可能支持各种场景跳转
      this.goRedirectUrl(redirectUrl);
    },
    handleClickSlide(e) { // Fix:自动轮播时，点击事件要加在swiper节点上，否则第二次轮播时click无响应
      console.log('adSwiper realIndex', this.$refs.swiper.$swiper.realIndex);
      const { realIndex } = this.$refs.swiper.$swiper;
      const product = this.adList[realIndex];
      console.log('ad', product);
      this.goToProduct(product);
    },
    imgError(ad) {
      // this.$store.commit('removeAd', ad);
    }
  },
  serverCacheKey: (props) => {
    return props.serverCacheKey;
  }
};
</script>

<style lang="less" scoped>
.ad_swipe {
  margin-top: 15px;
  .ad_img {
    width: 345px;
    height: 90px;
    img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}
</style>